const db = require('../models')

class CabinetRespositories {
  async addNewCabinet(cabinetData) {
    try {
      const newCabinet = await db.Cabinet.create(cabinetData);
      return newCabinet;
    } catch (error) {
      throw error;
    }
  }

  async delCabinetByNum(number) {
    const cabinet = await db.Cabinet.findOne({ where: { number } });
    return cabinet ? (await cabinet.destroy(), true) : false;
  }

  async updateCabinetByNum(number, cabinetData) {
    const [addectedRows] = await db.Cabinet.update(cabinetData, {
      where: { number },
    });
    return addectedRows > 0; // 返回是否更新成功
  }

  async getCabinetByNum(number) {
    return await db.Cabinet.findOne({ where: { number } });
  }

  async getCabinetsByGrpId(belongid) {
    return await db.Cabinet.findAll({ where: { belongid } });
  }

  async getAllCabinets() {
    return await db.Cabinet.findAll();
  }

  /* 根据 belong 和 `number` 返回快递柜信息 */
  async getCabinetByBelongAndNum(belong, number) {
    return await db.Cabinet.findOne({
      where: {
        belong,
        number,
      },
    });
  }
  /* 根据取件码获取 快递柜信息 */
  async getCabinetByQucode(quCode) {
    try {
      return await db.Cabinet.findOne({
        where: { quCode },
      });
    } catch (error) {
      throw error;
    }
  }

  async closeCabinetByNum(belong, number) {
    try {
      const [affectedRows] = await db.Cabinet.update(
        { isclosed: 1 },
        { where: { belong, number } }
      );
      return affectedRows > 0
    } catch (error) {
      throw error;
    }
  }
}
module.exports = new CabinetRespositories()
